from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.events import EVENT_JOB_ERROR, JobExecutionEvent
from datetime import datetime
from logger import log


def nowtime():
    print(datetime.now().strftime("%Y-%m-%d %H-%M-%S"))

    # 故意触发错误
    print(1/0)


def my_listener(event: JobExecutionEvent):
    log.logger.error(
        f"{event.exception} ouccurred in {event.job_id}...")
    global scheduler
    scheduler.remove_job(event.job_id)
    scheduler.shutdown(wait=False)


def main():
    global scheduler
    scheduler = BlockingScheduler()
    scheduler.add_job(func=nowtime, trigger="interval",
                      seconds=3, id="test_task")
    scheduler.add_listener(my_listener, EVENT_JOB_ERROR)
    scheduler._logger = log.logger
    scheduler.start()


if __name__ == "__main__":
    main()
